package com.borya.service.web.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.borya.constant.RedisConstant;
import com.borya.dao.SourceModelDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.model.entity.MerchantModelInfo;
import com.borya.model.entity.ModelDetail;
import com.borya.service.web.SourceModelService;
import com.borya.statuscode.StatusCode;
import com.borya.util.StringUtil;

@Component("sourceModelServiceImpl")
public class SourceModelServiceImpl implements SourceModelService{

	
	private Logger log = Logger.getLogger(getClass());
	
	@Autowired("sourceModelDAOImpl")
	private SourceModelDAO sourceModelDAO;
	
	public SourceModelDAO getSourceModelDAO() {
		return sourceModelDAO;
	}
	public void setSourceModelDAO(SourceModelDAO sourceModel) {
		this.sourceModelDAO = sourceModel;
	}
	
	@Override
	public String merchantInfo(String dealerId, int type) {
		MerchantModelInfo info = getSourceModelDAO().getMerchantModel(dealerId, type);
		if(info == null){
			log.warn("getMerchantModel return null");
			return StatusCode.USER_NOT_FOUND.toJSON();
		}
		String data = JSON.toJSONString(info, SerializerFeature.WriteNonStringValueAsString,SerializerFeature.WriteNullStringAsEmpty);
		return StatusCode.SUCCESS.toDiyJson(true, "data", data);
	}

	@Override
	public String modelList() {
		JSONObject data = getSourceModelDAO().modelList();
		if(data == null){
			log.warn("modelList return null");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		return StatusCode.SUCCESS.toDiyJson("data", data);
	}

	@Override
	public String updMerchant(MerchantModelInfo info, int type) {
		boolean res = getSourceModelDAO().updMerchant(info, type);
		if(! res){
			log.warn("updMerchant return false");
			return StatusCode.AUTHORIZE_FAILED.toJSON("操作失败");
		}
		return StatusCode.SUCCESS.toJSON();
	}

	@Override
	public String detailList() {
		try {
			JSONObject data = new JSONObject();
			final JSONArray phoneList = new JSONArray();
			final JSONArray packList = new JSONArray();
			data.put("phoneList", phoneList);
			data.put("packList", packList);
			//(表tb_phone_resource分组phone_model_type)
			String phoneStrs = getSourceModelDAO().allModelDetailStr1("tb_phone_resource", "phone_model_type");
			if(!StringUtil.isNULL(phoneStrs)){
				List<String> asList = Arrays.asList(phoneStrs.split(","));
				asList.forEach(e-> {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("name", e);
					phoneList.add(jsonObject);});
			}
			//(表tb_number_level_rule分组resource_model)
			String numberStrs = getSourceModelDAO().allModelDetailStr1("tb_number_level_rule", "resource_model");
			if(!StringUtil.isNULL(numberStrs)){
				List<String> asList1 = Arrays.asList(numberStrs.split(","));
				asList1.forEach(e-> {
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("name", e);
							packList.add(jsonObject);});
			}
/******************************old version**************************************/			
//			final String allModels = getSourceModel().allModelDetailStr(1);
//			if(allModels == null){
//				log.info("allModelDetailStr return null,type:"+1);
//				return StatusCode.SYSTEM_EXCEPTION.toJSON();
//			}
//			Set<String> set = new HashSet<>();
//			for(String str : allModels.split(",")){
//				if(! set.contains(str)){
//					JSONObject each = new JSONObject();
//					each.put("name", str);
//					phoneList.add(each);
//					set.add(str);
//				}
//			}
//			
//			final String allModels1 = getSourceModel().allModelDetailStr(4);
//			if(allModels1 == null){
//				log.info("allModelDetailStr return null,type:"+1);
//				return StatusCode.SYSTEM_EXCEPTION.toJSON();
//			}
//			Set<String> set1 = new HashSet<>();
//			for(String str : allModels1.split(",")){
//				if(! set1.contains(str)){
//					JSONObject each = new JSONObject();
//					each.put("name", str);
//					packList.add(each);
//					set1.add(str);
//				}
//			}
			return StatusCode.SUCCESS.toDiyJson("data", data);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return StatusCode.SYSTEM_EXCEPTION.toJSON();
	}

	@Override
	public String addDetail(ModelDetail detail,int modelType) {
		boolean res = getSourceModelDAO().addDetail(detail, modelType);
		if(! res){
			log.warn("addDetail return false,"+detail.toString());
			return StatusCode.AUTHORIZE_FAILED.toJSON("操作失败");
		}
		return StatusCode.SUCCESS.toJSON();
	}

	@Override
	public String detail(int modelId, int modelType) {
		switch (modelType) {
		case 1:
			return getSourceModelDetail(modelId);
		case 2:
			return getDiscountModelDetail(modelId);
		default:
			return getTransModelDetail(modelId);
		}
		
	}

	@Override
	public String updDetail(ModelDetail detail,int modelType) {
		boolean res = getSourceModelDAO().updDetail(detail, modelType);
		if(! res){
			log.warn("updDetail return false,"+detail.toString());
			return StatusCode.AUTHORIZE_FAILED.toJSON("操作失败");
		}
		return StatusCode.SUCCESS.toJSON();
	}

	/**
	 * 获取资源模式详情
	 * @param modelId
	 * @return
	 */
	private String getSourceModelDetail(int modelId){
		String phoneSourceStr = getSourceModelDAO().allModelDetailStr(1);
		String packSourceStr  = getSourceModelDAO().allModelDetailStr(4);
		if(phoneSourceStr == null || packSourceStr == null){
			log.warn("allModelDetailStr return null");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
			
		Set<String> phoneSet = new HashSet<>();
		for(String str : phoneSourceStr.split(",")){
			if(! phoneSet.contains(str)){
				phoneSet.add(str);
			}
		}
		Set<String> packSet = new HashSet<>();
		for(String str : packSourceStr.split(",")){
			if(! packSet.contains(str)){
				packSet.add(str);
			}
		}
		
		 ModelDetail detail = getSourceModelDAO().getSourceDetails(modelId);
		 if(detail == null){
			 log.warn("getSourceDetails return null,model:"+modelId);
			 return StatusCode.COMPANY_NOT_FOUND.toJSON("模式信息未找到");
		 }
		 JSONObject data = new JSONObject();
		 data.put("order", detail.getOrder()+"");
		 data.put("name", detail.getName());
		 data.put("descStr", detail.getDescStr());
		 data.put("detailType", detail.getDetailType()+"");
		 JSONArray detailList = new JSONArray();
		 if(detail.getDetailType() == 1){
			 List<String> detailStrs = Arrays.asList(detail.getDetailStr().split(","));
			 for(String str : phoneSet){
				 JSONObject each1 = new JSONObject();
				 each1.put("detail", str);
				 each1.put("value", detailStrs.contains(str)?"1":"2");
				 detailList.add(each1);
			 }
		 }
		 else{
			 List<String> detailStrs = Arrays.asList(detail.getDetailStr().split(","));
			 for(String str : packSet){
				 JSONObject each1 = new JSONObject();
				 each1.put("detail", str);
				 each1.put("value", detailStrs.contains(str)?"1":"2");
				 detailList.add(each1);
			 }
		 }
		 data.put("detailList", detailList);
		 return StatusCode.SUCCESS.toDiyJson("data", data);
	}
	
	/**
	 * 获取折扣模式详情
	 * @param modelId
	 * @return
	 */
	private String getDiscountModelDetail(int modelId){
		ModelDetail detail = getSourceModelDAO().getDiscountDetails(modelId);
		 if(detail == null){
			 log.warn("getDiscountDetails return null,model:"+modelId);
			 return StatusCode.COMPANY_NOT_FOUND.toJSON("模式信息未找到");
		 }
		 JSONObject each = new JSONObject();
		 each.put("order", detail.getOrder()+"");
		 each.put("name", detail.getName());
		 each.put("descStr", detail.getDescStr());
		 each.put("detailType", detail.getDetailType()+"");
		 each.put("countType", detail.getCountType()+"");
		 each.put("faceMoney", detail.getFaceMoney()+"");
		 each.put("discount", detail.getDiscount()+"");
		 each.put("incomeDiscount", detail.getIncomeDiscount()+"");
		 each.put("cityCode", detail.getCityCode()+"");
		 each.put("packPreCode", detail.getPackPreCode());
		 each.put("cityCodeName", detail.getCityName());
		 each.put("packPreDesc", detail.getPackPreCode()+"/code:"+detail.getPackPreCode());
		 return StatusCode.SUCCESS.toDiyJson("data", each);
	}
	
	/**
	 * 获取转账模式详情
	 * @param modelId
	 * @return
	 */
	private String getTransModelDetail(int modelId){
		ModelDetail detail = getSourceModelDAO().getTransDetail(modelId);
		if(detail == null){
			log.warn("getTransDetail return null,model:"+modelId);
			return StatusCode.COMPANY_NOT_FOUND.toJSON("模式信息未找到");
		}
		JSONObject data = new JSONObject();
		data.put("order", detail.getOrder()+"");
		data.put("name", detail.getName());
		data.put("descStr", detail.getDescStr());
		data.put("trans", detail.getTrans()+"");
		data.put("alification", detail.getAlification()+"");
		return StatusCode.SUCCESS.toDiyJson("data", data);
	}

	@Override
	public String modelDetailList(int modelType) {
		List<ModelDetail> list = getSourceModelDAO().getModelDetailList(modelType);
		if(list == null){
			log.error("getModelDetailList return null");
			return StatusCode.SYSTEM_EXCEPTION.toJSON();
		}
		JSONObject data = new JSONObject();
		JSONArray detailList = new JSONArray();
		data.put("detailList", detailList);
		
		switch (modelType) {
		case 1:
			for(int i = 0,size = list.size();i < size; i++){
				ModelDetail detail = list.get(i);
				JSONObject each = new JSONObject();
				detailList.add(each);
				each.put("order", detail.getOrder()+"");
				each.put("name", detail.getName());
				each.put("createTime", detail.getCreateTimeStr());
				each.put("detailType", detail.getDetailType()+"");
				each.put("detailStr", detail.getDetailStr());
				each.put("descStr", detail.getDescStr());
			}
			break;
		case 2:
			Map<String, String> packTitle = getSourceModelDAO().getPackTitles();
			if(packTitle == null){
				log.warn("查询套餐标题失败");
				return StatusCode.SYSTEM_EXCEPTION.toJSON();
			}
			for(int i = 0,size = list.size();i < size; i++){
				ModelDetail detail = list.get(i);
				JSONObject each = new JSONObject();
				detailList.add(each);
				each.put("order", detail.getOrder()+"");
				each.put("name", detail.getName());
				each.put("createTime", detail.getCreateTimeStr());
				each.put("countType", detail.getCountType()+"");
				each.put("detailType", detail.getDetailType()+"");
				each.put("faceMoney", detail.getFaceMoney()+"");
				each.put("discount", detail.getDiscount()+"");
				each.put("incomeDiscount", detail.getIncomeDiscount()+"");
				each.put("cityCodeName", detail.getCityName());
				String packPreDesc = packTitle.get(detail.getPackCode());
				each.put("packPreDesc", packPreDesc == null?"":packPreDesc+"/"+detail.getPackPre());
				each.put("descStr", detail.getDescStr());
			}
			break;
		default:
			for(int i = 0,size = list.size();i < size; i++){
				ModelDetail detail = list.get(i);
				JSONObject each = new JSONObject();
				detailList.add(each);
				each.put("order", detail.getOrder()+"");
				each.put("name", detail.getName());
				each.put("createTime", detail.getCreateTimeStr());
				each.put("trans", detail.getTrans()+"");
				each.put("alification", detail.getAlification()+"");
				each.put("descStr", detail.getDescStr());
			}
			break;
		}
		return StatusCode.SUCCESS.toDiyJson("data", data);
	}

	@Override
	public String getCityList() {
		String city_key = RedisConstant.SET_CITY_KEY;
		String citys = getSourceModelDAO().redis_get(city_key);
		if(null == citys){
			JSONObject msg = getSourceModelDAO().getCityList();
			if(null == msg){
				log.warn("getCityList return null");
			}
			boolean a = getSourceModelDAO().redis_set(city_key, msg.toString());
			boolean b = getSourceModelDAO().redis_expire(city_key,30*60);
			log.debug("redis保存城市  值:时间->"+a+":"+b);
			if(!a || !b){
				//to do nothing
			}
			return StatusCode.SUCCESS.toDiyJson("data", msg);
		}else{
			return StatusCode.SUCCESS.toDiyJson("data", JSONObject.parseObject(citys));
		}
	}

	@Override
	public String packPreList() {
		String city_key = RedisConstant.SET_PACKPRE_KEY;
		String arrInfo = getSourceModelDAO().redis_get(city_key);
		JSONArray arr = null;
		if(null == arrInfo){
			arr = getSourceModelDAO().getPackPreList();
			if(null == arr){
				log.warn("getPackPreList return null");
			}
			boolean a = getSourceModelDAO().redis_set(city_key, arr.toString());
			boolean b = getSourceModelDAO().redis_expire(city_key,15*60);
			log.debug("redis保存联通套餐预存  值:时间->"+a+":"+b);
//			if(!a || !b){
//			}
		}
		else{
			arr = JSONArray.parseArray(arrInfo);
		}
		JSONObject data = new JSONObject();
		data.put("packPreList", arr);
		return StatusCode.SUCCESS.toDiyJson("data", data);
	}
	
}